package jp.sourceforge.talisman.csvio;

/*
 * $Id: CsvLine.java,v 1.1 2009/09/12 05:06:12 weiwei Exp $
 */

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * This class presented a row of csv file.
 *
 * @author Haruaki TAMADA
 * @version $Revision: 1.1 $ $Date: 2009/09/12 05:06:12 $
 */
public class CsvLine implements Iterable<String>, Serializable, Cloneable{
    private static final long serialVersionUID = 7406197507497201455L;

    /**
     * element container.
     */
    private List<CsvElement> elements = new ArrayList<CsvElement>();

    /**
     * Default constructor.
     */
    public CsvLine(){
    }

    /**
     * copy constructor
     */
    public CsvLine(CsvLine line){
        for(String value: line){
            addValue(value);
        }
    }

    /**
     * Constructor with given values.
     */
    public CsvLine(String[] values){
        for(int i = 0; i < values.length; i++){
            addValue(values[i]);
        }
    }

    /**
     * return the number of element count of this line
     */
    public synchronized int size(){
        return elements.size();
    }

    /**
     * add a element to the last position of this line.
     * @param value
     */
    public synchronized void addValue(String value){
        elements.add(new CsvElement(value));
    }

    /**
     * add a element to the specified index of this line.
     */
    public synchronized void addValue(int index, String element){
        elements.add(index, new CsvElement(element));
    }

    /**
     * return a element located at specified index of this line. 
     */
    public synchronized String getValue(int index){
        return elements.get(index).getValue();
    }

    /**
     * remove a element located at specified index from this line.
     */
    public synchronized void removeValue(int index){
        elements.remove(index);
    }

    /**
     * return the array of elements of this line.
     */
    public synchronized String[] getValues(){
        String[] strings = new String[elements.size()];
        for(int i = 0; i < strings.length; i++){
            strings[i] = elements.get(i).getValue();
        }

        return strings;
    }

    /**
     * return the enumeration of elements of this line.
     */
    public Iterator<String> iterator(){
        return new Iterator<String>(){
            private List<CsvElement> newList = new ArrayList<CsvElement>(elements);
            private Iterator<CsvElement> iterator = newList.iterator();

            public boolean hasNext(){
                return iterator.hasNext();
            }

            public String next(){
                return iterator.next().getValue();
            }

            public void remove(){
                iterator.remove();
            }
        };
    }
    
    public Object clone(){
        return new CsvLine(this);
    }
}
